import 'package:boss/http/api/api_helper.dart';
import 'package:boss/http/api/url_apis.dart';
import 'package:boss/main.dart';
import 'package:boss/models/analysis_detail.dart';
import 'package:boss/textStyle/text_style.dart';
import 'package:boss/ui/page/analysis/page/analysisDetail/model/analysis_detail_type.dart';
import 'package:boss/ui/page/analysis/page/analysisDetail/widget/table_header.dart';
import 'package:boss/ui/page/analysis/page/analysisDetail/widget/table_row.dart' as tableRow;
import 'package:boss/ui/page/analysis/widget/button_group.dart';
import 'package:boss/ui/page/analysis/widget/time_row.dart';
import 'package:boss/ui/page/reportForm/util/dialog.dart';
import 'package:boss/ui/widget/calendar/calendar.dart';
import 'package:boss/ui/widget/calendar/util/date_util.dart';
import 'package:boss/ui/widget/center_title_app_bar.dart';
import 'package:boss/ui/widget/image/base_image.dart';
import 'package:boss/ui/widget/loader/loader_pull_refresh.dart';
import 'package:boss/ui/widget/shadow_radius_card.dart';
import 'package:boss/ui/widget/split_line.dart';
import 'package:hi_common/hi_common.dart';
import 'package:flustars/flustars.dart' as flustars;
import 'package:flutter/material.dart';
import 'package:router/annotation.dart';

import 'widget/data_panel_row.dart';
import 'package:async/async.dart';

@RouterConfig(AnalysisDetailPage.pageName)
class AnalysisDetailPage extends StatefulWidget {
  static const String pageName = '/analysisDetailPage';

  @Autowired()
  final AnalysisDetailType type;

  @Autowired()
  final DateTime startTime;

  @Autowired()
  final DateTime endTime;

  const AnalysisDetailPage({this.type, this.startTime, this.endTime});

  @override
  _AnalysisDetailPageState createState() => _AnalysisDetailPageState('查看明细');
}

class _AnalysisDetailPageState extends BaseState<AnalysisDetailPage> {
  _AnalysisDetailPageState(String pageName) : super(pageName);

  int index = 0;

  DateTime startTime;
  DateTime endTime;

  String get startTimeText => flustars.DateUtil.formatDate(startTime);

  String get endTimeText => flustars.DateUtil.formatDate(endTime);

  String get rangeTimeText =>
      '${flustars.DateUtil.formatDate(startTime, format: flustars.DateFormats.y_mo_d)}至${flustars.DateUtil.formatDate(endTime, format: flustars.DateFormats.y_mo_d)}';

  AnalysisDetail data;

  GlobalKey<LoaderPullRefreshState> refreshKey = GlobalKey<LoaderPullRefreshState>();

  @override
  void initState() {
    super.initState();

    startTime = widget.startTime;
    endTime = widget.endTime;

    final now = DateTime.now();

    final startToday = DateUtils.startOfTheDay(now);
    final endToday = DateUtils.endOfTheDay(now);

    final startYesterday = startToday.subtract(Duration(days: 1));
    final endYesterday = DateUtils.endOfTheDay(startYesterday);

    final startMonth = DateUtils.startOfTheMonth(now);
    final endMonth = DateUtils.endOfTheMonth(now);

    final prevStartMonth = DateUtils.startOfPrevMonth(now);
    final prevEndMonth = DateUtils.endOfTheMonth(prevStartMonth);

    if (startTime.isAtSameMomentAs(startToday) && endTime.isAtSameMomentAs(endToday)) {
      index = 1;
    } else if (startTime.isAtSameMomentAs(startYesterday) && endTime.isAtSameMomentAs(endYesterday)) {
      index = 0;
    } else if (startTime.isAtSameMomentAs(startMonth) && endTime.isAtSameMomentAs(endMonth)) {
      index = 2;
    } else if (startTime.isAtSameMomentAs(prevStartMonth) && endTime.isAtSameMomentAs(prevEndMonth)) {
      index = 3;
    } else {
      index = 4;
    }
  }

  @override
  Widget build(BuildContext context) {
    return DefaultTextStyle(
      style: TextStyleConstant().normal_1_28,
      child: Scaffold(
        appBar: CenterTitleAppBar(
          title: super.pageName,
          actions: <Widget>[
            GestureDetector(
              child: BaseImage(
                'assets/image/download_icon.png',
                width: 40.w,
                height: 40.w,
              ),
              onTap: () {
                showChangeEmailAlert(
                  context,
                  onConfirm: (email) async {
                    Navigator.pop(context);

                    final map = {
                      AnalysisDetailType.commodityCommissionSort: Apis.sendEmailStoreRoyaltyDetailForTime,
                      AnalysisDetailType.takeoutSellSort: null,
                      AnalysisDetailType.tipSort: Apis.sendEmailStoreTipDetailForTime,
                    };

                    final res = await analyticSMS(
                      startTime: startTimeText,
                      endTime: endTimeText,
                      email: email,
                      url: map[widget.type],
                    );

                    toast(res['code'] == HttpRespCode.OK ? '发送成功' : res['msg']);
                  },
                );
              },
            ),
          ],
        ),
        body: Column(
          children: <Widget>[
            ButtonGroup(
              buttons: ['昨日', '今日', '本月', '上月', '自定义'],
              selectedIndex: index,
              onChanged: onDateChange,
              height: 60.w,
              margin: EdgeInsets.only(left: 30.w, right: 30.w, top: 20.w, bottom: 20.w),
            ),
            Expanded(
              child: LoaderPullRefresh(
                key: refreshKey,
                refreshTask: refreshTask,
                builder: (context) {
                  return SingleChildScrollView(
                    padding: EdgeInsets.symmetric(horizontal: 30.w),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        TimeRow('$rangeTimeText'),
                        if (widget.type != AnalysisDetailType.staffCommissionList && widget.type != AnalysisDetailType.book)
                          ShadowRadiusCard(
                            padding: EdgeInsets.symmetric(vertical: 38.w),
                            margin: EdgeInsets.only(bottom: 30.w),
                            child: Row(
                              children: <Widget>[
                                DataPanelRow('共计', data.count, data.priceCount),
                                SplitLine(
                                  height: 80.w,
                                ),
                                DataPanelRow('已分账', data.alreadyDisCount, data.alreadyDisPriceCount),
                                SplitLine(
                                  height: 80.w,
                                ),
                                DataPanelRow('待分账', data.waitDistributeCount, data.waitDistributePriceCount),
                              ],
                            ),
                          ),
                        TableHeader(widget.type),
                        ...data.list.map((item) => tableRow.TableRow(item, widget.type)).toList(),
                      ],
                    ),
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  Future<Result<List>> refreshTask() async {
    try {
      if (widget.type == AnalysisDetailType.book) {
        final res = await api.queryStoreStaffForTime(
          startTime: startTimeText,
          endTime: endTimeText,
        );

        if (!res.successful()) {
          return Result.error(res.msg);
        }

        setState(() {
          final temp = AnalysisDetail();
          temp.list = res.data.bookListSort.map((item) {
            AnalysisDetailItem data = AnalysisDetailItem.fromJson({
              'name': item.waiterName,
              'tableCount': item.bookTableNum,
            });

            final finder = res.data.staffCommissionList.firstWhere((element) => element.waiterId == item.waiterId, orElse: () => null);
            if (finder != null) {
              data.money = finder.amount;
            } else {
              data.money = 0;
            }

            return data;
          }).toList();
          data = temp;
        });

        return Result.value([]);
      } else {
        final res = await queryStaffAnalysisDetailForTime(
          startTime: startTimeText,
          endTime: endTimeText,
          type: widget.type,
        );

        if (res.code != HttpRespCode.OK) {
          return Result.error(res.msg);
        }

        setState(() {
          data = res.data;
        });

        return Result.value([]);
      }
    } catch (e) {
      return Result.error(e.toString());
    }
  }

  onDateChange(int index) async {
    this.index = index;
    bool isRefresh = true;

    if (index == 0) {
      var yesterday = DateTime.now().subtract(Duration(days: 1));

      startTime = DateUtils.startOfTheDay(yesterday);
      endTime = DateUtils.endOfTheDay(yesterday);
    } else if (index == 1) {
      var now = DateTime.now();

      startTime = DateUtils.startOfTheDay(now);
      endTime = DateUtils.endOfTheDay(now);
    } else if (index == 2) {
      var now = DateTime.now();

      startTime = DateUtils.startOfTheMonth(now);
      endTime = DateUtils.endOfTheMonth(now);
    } else if (index == 3) {
      var now = DateTime.now();

      startTime = DateUtils.startOfPrevMonth(now);
      endTime = DateUtils.endOfPrevMonth(now);
    } else {
      var res = await showCalendar(
        context,
        minDateTime: DateTime(1996),
        startDateTime: startTime,
        endDateTime: endTime,
      );

      if (res != null) {
        startTime = res[0];
        endTime = res[1];
      } else {
        isRefresh = false;
      }
    }

    setState(() {});

    if (isRefresh) refreshKey.currentState.refresh();
  }
}
